// Description: 注入到页面的脚本
(() => {
    initCssStyle();
    initMakeAllWords()
})();

function initMakeAllWords() {
    chrome.storage.local.get('words', function (result) {
        let allWords = result.words || [];
        allWords.forEach(function (word) {
            makeTextColor(word.colorIndex, word.word);
        });
    });
}

//初始化样式
function initCssStyle() {
    let style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = `
    ep-red-tag,ep-orange-tag ,ep-yellow-tag ,ep-green-tag ,ep-blue-tag ,ep-indigo-tag ,ep-purple-tag{
        border-radius:2px;
    } 
    ep-red-tag {
        background-color: #FF2C2C;
        color: white;
    }
    ep-orange-tag {
        background-color: #ff6600;
        color: white;
    }
    ep-yellow-tag {
        background-color: #FFE82C;
        color: black;
    }
     ep-green-tag {
        background-color: #1bd126;
        color: black;
    }
    ep-blue-tag {
        background-color: #3641FF;
        color: white;
    }
 
    ep-indigo-tag {
        background-color: indigo;
        color: white;
    }
    
    ep-purple-tag {
        background-color: purple;
        color: white;
    }
`;
    document.head.appendChild(style);
}


//获取鼠标选中的内容
function getSelectedText() {
    let text = '';
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type !== 'Control') {
        text = document.selection.createRange().text;
    }
    return text.trim();
}

const Global = {
    selectedText: '',
    colors: ['red', 'yellow', 'blue', 'green', 'orange', 'indigo', 'purple',]
}

//监听鼠标选中的文本
document.onmousemove = document.onmouseup = function () {
    let text = getSelectedText();
    if (text) {
        Global.selectedText = text;
    }
}

function unMarkTextColor(index, text) {
    if (!text) {
        return;
    }
    let body = document.body;
    const theWordElement = '<ep-' + Global.colors[index] + '-tag>' + text + '</ep-' + Global.colors[index] + '-tag>';
    //创建正则表达式(搜索包含这个单词的文本)
    let reg = new RegExp(theWordElement, 'g');
    body.innerHTML = body.innerHTML.replace(reg, text);
}

async function makeTextColor(index, text) {
    if (!text) {
        return;
    }

    //遍历一下，看是否已经被标记过了，如果标记过了，则删除这个标记，然后继续
    for (let i = 0; i < Global.colors.length; i++) {
        if (document.body.innerHTML.indexOf('<ep-' + Global.colors[i] + '-tag>' + text + '</ep-' + Global.colors[i] + '-tag>') !== -1) {
            await deleteWord(text);
            break;
        }
    }

    //将文字标记成想要的颜色
    let body = document.body;
    //创建正则表达式(搜索包含这个单词的文本)
    let reg = new RegExp(text, 'g');
    //遍历网页中所有的文本元素并替换
    let textNodes = getTextNodes(body);
    textNodes.forEach(function (node) {
        if (node.nodeValue && node.nodeValue.indexOf(text) !== -1) {
            //console.log("node",node)
            let html = node.nodeValue.replace(reg, '<ep-' + Global.colors[index] + '-tag>' + text + '</ep-' + Global.colors[index] + '-tag>');
            let div = document.createElement('div');
            div.innerHTML = html;
            while (div.firstChild) {
                node.parentNode.insertBefore(div.firstChild, node);
            }
            node.parentNode.removeChild(node);
        }
    });
}

function getTextNodes(node) {
    let nodes = [];
    //console.log(node.nodeType, node.nodeName, node.nodeValue)
    if (node.nodeType === Node.TEXT_NODE) {
        nodes.push(node);
    } else {
        let children = node.childNodes;
        for (let i = 0; i < children.length; i++) {
            nodes.push(...getTextNodes(children[i]));
        }
    }
    return nodes;
}

async function deleteWord(text) {
    return new Promise(resolve => {
        chrome.storage.local.get('words', function (result) {
            let words = result.words || [];
            let theWord = words.find(item => item.word === text);
            if (theWord) {
                unMarkTextColor(theWord.colorIndex, theWord.word);
                //delete the word
                let newWords = words.filter(item => !(item.word === text));
                chrome.storage.local.set({words: newWords}, function () {
                    console.log('deleteWord success', JSON.stringify(newWords.map(item => item.word)));
                    resolve(newWords.map(item => item.word));
                });
            }
        });
    })

}

//监听按键事件
document.onkeydown = async function (e) {
    if (!Global.selectedText || !Global.selectedText.trim()) {
        return;
    }
    e = e || window.event;
    if (e.key === '0' || e.key === 'Escape') {
        await deleteWord(Global.selectedText);
        return;
    }
    //1-7分别对应赤橙黄绿青蓝紫
    const index = parseInt(e.key) - 1;
    if (isNaN(index) || index < 0 || index >= Global.colors.length) {
        Global.selectedText = '';
        console.log("invalid color index", index)
        return;
    }
    await makeTextColor(index, Global.selectedText);
    saveWord(index, Global.selectedText);
    Global.selectedText = '';
}

function saveWord(colorIndex, word) {
    let userId = getUserId();
    let url = window.location.href;
    let domain = window.location.hostname;
    let data = {
        userId: userId,
        domain: domain,
        url: url,
        word: word,
        colorIndex: colorIndex,
        color: Global.colors[colorIndex],
        createdDate: new Date().getTime(),
    }
    // chrome.runtime.sendMessage({action: 'SaveWord', data: data}, function (response) {
    //     console.log('saveWord response', response);
    // });
    chrome.storage.local.get('words', function (result) {
        let words = result.words || [];
        //if not exists
        let exists = words.find(item => item.word === data.word);
        if (exists) {
            return;
        }
        //save
        words.push(data);
        chrome.storage.local.set({words: words}, function () {
            console.log('saveWord success', JSON.stringify(words.map(item => item.word)));
        });
    });
}


function getUserId() {
    let userId = localStorage.getItem('userId');
    if (userId) {
        return userId;
    } else {
        if (navigator.userAgent.indexOf('Chrome') !== -1) {
            let chrome = window.chrome || {};
            userId = chrome.runtime.id;
        } else {
            userId = Math.random().toString(36).substring(2);
        }
        localStorage.setItem('userId', userId);
        return userId;
    }
}
